package service

import (
	"context"
	"errors"
	"github.com/wonderivan/logger"
	nwv1 "k8s.io/api/networking/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/json"
	"time"
	"unsafe"
)

var Ingress ingress

type ingress struct{}

type IngressesResp struct {
	Items []nwv1.Ingress `json:"items"`
	Total int            `json:"total"`
}

type ingressCell nwv1.Ingress

func (i ingressCell) GetCreation() time.Time {
	return i.CreationTimestamp.Time
}
func (i ingressCell) GetName() string {
	return i.Name
}

func (i *ingress) toCells(std []nwv1.Ingress) []DataCell {
	cells := make([]DataCell, len(std))
	for s := range std {
		cells[s] = ingressCell(std[s])
	}
	return cells
}
func (i *ingress) fromCells(cells []DataCell) []nwv1.Ingress {
	ingresses := make([]nwv1.Ingress, len(cells))
	for i := range cells {
		ingresses[i] = nwv1.Ingress(cells[i].(ingressCell))
	}
	return ingresses
}

func (i *ingress) GetIngresses(filterName, namespace string, limit, page int) (ingressesResp *IngressesResp, err error) {
	ingressesList, err := K8s.ClientSet.NetworkingV1().Ingresses(namespace).List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("获取ingress列表失败," + err.Error()))
		return nil, errors.New("获取ingress列表失败," + err.Error())
	}
	selectableData := &dataSelector{
		GenericDataList: i.toCells(ingressesList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData.Filter()
	total := len(filtered.GenericDataList)
	data := filtered.Sort().Paginate()
	ingreses := i.fromCells(data.GenericDataList)
	return &IngressesResp{
		Items: ingreses,
		Total: total,
	}, nil
}

func (i *ingress) GetIngressDetail(namespace, ingressname string) (data *nwv1.Ingress, err error) {
	data, err = K8s.ClientSet.NetworkingV1().Ingresses(namespace).Get(context.TODO(), ingressname, metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取ingress失败," + err.Error()))
		return nil, errors.New("获取ingress失败," + err.Error())
	}
	return data, nil
}

//type IngressCreate struct{
//	Namespace string	`json:"namespace"`
//	Name		string		`json:"name"`
//	//Annotations 	map[string]string	`json:"annotations"`
//	IngressClassName	string	`json:"ingressclassname"`
//	HostUrl		string		`json:"hosturl"`
//	HttpPath	string		`json:"httppath"`
//	HttpPathType	nwv1.PathType			`json:"httppathtype"`
//	ServiceName		string		`json:"servicename"`
//	ServicePort		int32		`json:"serviceport"`
//}

// 换一个方式实现，支持多个子路径的。下面这种暂时不支持。
//func(i *ingress)CreateIngress(data *IngressCreate)(err error){
//	ingress := &nwv1.Ingress{
//		ObjectMeta: metav1.ObjectMeta{
//			Name: data.Name,
//			Namespace: data.Namespace,
//			//Annotations: data.Annotations,
//		},
//		// 这段代码的缺点就是：对于ingress带有多个子路径的，需要循环设置，不太友好，。可以不用这种方法。
//		Spec: nwv1.IngressSpec{
//			IngressClassName: &data.IngressClassName,
//			//DefaultBackend: &data.
//			Rules: []nwv1.IngressRule{
//				// 这里是数组
//				{
//					Host: data.HostUrl,
//					// 从源码来看IngressRuleValue没有定义变量，只写了个IngressRuleValue，因此这里我们需要加上IngressRuleValue变量，然后写上nwv1.IngressRuleValue
//					// 技巧：当不知道是否需要加上 "nwv1." 的时候,就点开源码，看看这个文件隶属于那个文件里面，比如IngressRuleValue，隶属于"k8s.io/api/networking/v1"目录下。
//					IngressRuleValue: nwv1.IngressRuleValue{
//						HTTP: &nwv1.HTTPIngressRuleValue{
//							Paths: []nwv1.HTTPIngressPath{
//								// 这里是数组
//								{
//									Path: data.HttpPath,
//									PathType: &data.HttpPathType,
//									Backend: nwv1.IngressBackend{
//										Service: &nwv1.IngressServiceBackend{
//											Name: data.ServiceName,
//											Port: nwv1.ServiceBackendPort{
//												Number: data.ServicePort,
//											},
//										},
//									},
//								},
//							},
//						},
//					},
//				},
//			},
//		},
//	}
//	_,err = K8s.ClientSet.NetworkingV1().Ingresses(data.Namespace).Create(context.TODO(),ingress,metav1.CreateOptions{})
//	if err != nil{
//		logger.Error(errors.New("创建ingress失败," + err.Error()))
//		return errors.New("创建ingress失败," + err.Error())
//	}
//	return nil
//}

//定义ServiceCreate的结构体，用于创建service需要的参数属性的定义

type IngressCreate struct {
	Name      string                 `json:"name"`
	Namespace string                 `json:"namespace"`
	Hosts     map[string][]*HttpPath `json:"hosts"`
}

type HttpPath struct {
	Path        string        `json:"path"`
	PathType    nwv1.PathType `json:"pathtype"`
	ServiceName string        `json:"servicename"`
	ServicePort int32         `json:"serviceport"`
}

func (i *ingress) CreateIngress(data *IngressCreate) (err error) {
	var ingressRules []nwv1.IngressRule
	var httpIngressPATHs []nwv1.HTTPIngressPath



	ingress := &nwv1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:      data.Name,
			Namespace: data.Namespace,

			// annotations暂时设置为固定值
			Annotations: map[string]string{
				"kubernetes.io/ingress.class": "nginx",
			},
		},
		Status: nwv1.IngressStatus{},
	}
	// 第一层for循环是将host组装成nwv1.IngressRule类型的对象
	// 一个host对于一个ingressrule，每个ingressrule中包含一个host和多个path
	for key, value := range data.Hosts {
		ir := nwv1.IngressRule{
			Host: key,
			IngressRuleValue: nwv1.IngressRuleValue{
				HTTP: &nwv1.HTTPIngressRuleValue{Paths: nil},
			},
		}
		// 第二层for循环是将path组装成nwv1.HTTPIngressPath类型的对象
		for _, httpPath := range value {
			hip := nwv1.HTTPIngressPath{
				Path:     httpPath.Path,
				PathType: &httpPath.PathType,
				Backend: nwv1.IngressBackend{
					Service: &nwv1.IngressServiceBackend{
						//workflow做get操作返回结果的时候加上"-svc"的后缀，其他动作不加此后缀。
						//Name: getServiceNameSvc(httpPath.ServiceName),
						Name: httpPath.ServiceName,
						Port: nwv1.ServiceBackendPort{
							Number: httpPath.ServicePort,
						},
					},
				},
			}
			//将每个hip对象组装成属组
			httpIngressPATHs = append(httpIngressPATHs, hip)
		}
		// 给Paths赋值，前面置为空了
		ir.IngressRuleValue.HTTP.Paths = httpIngressPATHs
		// 将每个ir对象组装成属组，这个ir对象就是IngressRule，每个元素是一个host和多个path
		ingressRules = append(ingressRules, ir)
	}
	//将IngressRules对象加入到ingress的规则中
	ingress.Spec.Rules = ingressRules
	//创建ingress
	_, err = K8s.ClientSet.NetworkingV1().Ingresses(data.Namespace).Create(context.TODO(), ingress, metav1.CreateOptions{})
	if err != nil {
		logger.Error(errors.New("创建ingress失败," + err.Error()))
		return errors.New("创建ingress失败," + err.Error())
	}
	return nil
}

//workflow名字转换成service名字，添加-svc后缀
func getServiceNameSvc(workflowName string) (serviceName string) {
	return workflowName + "-svc"
}

func (i *ingress) DeleteIngress(namespace, name string) (err error) {
	err = K8s.ClientSet.NetworkingV1().Ingresses(namespace).Delete(context.TODO(), name, metav1.DeleteOptions{})
	if err != nil {
		logger.Error(errors.New("删除ingress规则失败," + err.Error()))
		return errors.New("删除ingress规则失败," + err.Error())
	}
	return nil
}

func StringToBytes(data string) []byte {
	return *(*[]byte)(unsafe.Pointer(&data))
}

func (i *ingress) UpdateIngress(namespace, content string) (err error) {
	var ingress = &nwv1.Ingress{}
	//将content从string反序列到json
	err = json.Unmarshal(StringToBytes(content), ingress)
	if err != nil {
		logger.Error(errors.New("反序列化失败," + err.Error()))
		return errors.New("反序列化失败," + err.Error())
	}
	_, err = K8s.ClientSet.NetworkingV1().Ingresses(namespace).Update(context.TODO(), ingress, metav1.UpdateOptions{})
	if err != nil {
		logger.Error(errors.New("更新service失败," + err.Error()))
		return errors.New("更新service失败," + err.Error())
	}
	return nil
}
